package com.yunshipei.ui.fragment;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yunshipei.EnterApplication;
import com.yunshipei.adapter.SortAdapter;
import com.yunshipei.base.BaseSubscriberAdapter;
import com.yunshipei.common.Globals;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.YspEvent.UserAvatarChangedEvent;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.SetupPhotoDialog;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.CheckSdCard;
import com.yunshipei.utils.FileUtils;
import com.yunshipei.utils.StringUtil;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;

public class CustomerInfoFragment extends Fragment implements View.OnClickListener {

    @Bind(R.id.nametitle)
    protected TextView nameTitle;
    @Bind(R.id.titlePor)
    protected ImageView titlePor;
    @Bind(R.id.nametv)
    protected TextView nameTv;
    @Bind(R.id.positiontv)
    protected TextView position;
    @Bind(R.id.fl_img_container)
    protected View vAvatar;
    @Bind(R.id.photo_frame)
    protected ImageView photoView;

    private UserInfo yspUserInfo;
    private SharedPreferences mySharedPreferences;

    private static final int PHOTO_REQUEST_CAMERA = 1;        //相机拍照
    private static final int PHOTO_REQUEST_GELLERY = 2;        //图库选择
    private static final int PHOTO_REQUEST_CUT = 3;            //图片裁减

    private String PHOTO_FILE_NAME = StringUtilSub.getPhotoFileName();
    private Bitmap bitmap;
    File tempFile = null;
    private File tempShearFile = null;
    private String imgCachePath = "";

    public static CustomerInfoFragment newInstances(UserInfo userInfo) {
        CustomerInfoFragment customerInfoFragment = new CustomerInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Globals.DATA_USER_INFO, userInfo);
        customerInfoFragment.setArguments(bundle);
        return customerInfoFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mySharedPreferences = YspPreferences.getInstance().getSharedPreferences();
        this.imgCachePath = FileUtils.getEnterImgCachePath();
        this.yspUserInfo = (UserInfo) getArguments().getSerializable(Globals.DATA_USER_INFO);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_customer_detail, container, false);
        ButterKnife.bind(this, view);
        vAvatar.setOnClickListener(this);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        String nameStr = yspUserInfo.getName();
        if (!StringUtil.isEmpty(yspUserInfo.getAvatar())) {
            Glide.with(this).load(R.mipmap.ic_launcher).into(titlePor);
        } else if (!TextUtils.isEmpty(nameStr) && StringUtilSub.isChinese(nameStr)) {
            nameTitle.setText(SortAdapter.getEndword(nameStr));
        } else if (!TextUtils.isEmpty(nameStr)) {
            nameTitle.setText(nameStr.substring(0, 1).toUpperCase());
        }
//        String userName = yspUserInfo.getName();
//        if (TextUtils.isEmpty(userName)) {
//            nameTv.setVisibility(View.GONE);
//        } else {
            nameTv.setText(YspPreferences.getInstance().getSharedPreferences().getString("ADUserName",""));
       // }
//        String userPosition = yspUserInfo.getPosition();
//        if (TextUtils.isEmpty(userPosition)) {
//            position.setVisibility(View.GONE);
//        } else {
            position.setText(YspPreferences.getInstance().getSharedPreferences().getString("ADDomainAccount",""));
       // }
        GradientDrawable drawable = (GradientDrawable) photoView.getBackground();
        drawable.setColor(EnterConfig.getInstance().getGlobalColor());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_img_container:
//                final SetupPhotoDialog photoDialog = DialogHelper.getSetupPhotoDialog(getActivity());
//                photoDialog.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        photoDialog.dismiss();
//                        switch (v.getId()) {
//                            case R.id.open_camera:
//                                camera();
//                                break;
//                            case R.id.open_photo:
//                                gallery();
//                                break;
//                        }
//                    }
//                });
//                photoDialog.show();
                break;
        }
    }

    public void camera() {
        if (BaseUtil.isCameraAvailable()) {
            tempFile = new File(imgCachePath, PHOTO_FILE_NAME);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
            startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
        } else {
            ToastUtils.showToast(R.string.camera_permission_request);
        }
    }

    public void gallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, PHOTO_REQUEST_GELLERY);
    }

    private boolean flag = false;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GELLERY) {
            if (data != null) {
                Uri uri = data.getData();
                crop(uri, true);
            }
        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            tempFile = new File(imgCachePath, PHOTO_FILE_NAME);
            tempFile.setReadable(true);
            tempFile.setWritable(true);
            if (FileUtils.haveFile(tempFile)) {
                crop(Uri.fromFile(tempFile), false);
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            if (data == null && flag) {
                gallery();
                return;
            }
            try {
                if (FileUtils.haveFile(tempShearFile)) {
                    bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(Uri.fromFile(tempShearFile)));
                    bitmap = compressImage(bitmap);
                    tempFile = saveBitmap(bitmap);
                    //在这里上传
                    if (tempFile != null) {
                        HttpMethods.getInstance().modifyPersonalAvatar(tempFile, yspUserInfo.getUuid(), new AvatarSubscriber());
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    /*
     * 图片压缩
     */
    private Bitmap compressImage(Bitmap image) throws FileNotFoundException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 80, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        File file = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        FileOutputStream outputStream = new FileOutputStream(file);
        image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);
    }

    private class AvatarSubscriber extends BaseSubscriberAdapter<JSONObject> {

        @SuppressLint("CommitPrefEdits")
        @Override
        public void onNext(JSONObject jsonObject) {
            int status = jsonObject.optInt("status", 0);
            if (status == 1) {
                String imageUrl = jsonObject.optString("data");
                if (!TextUtils.isEmpty(imageUrl)) {
                    ToastUtils.showToast("修改成功");
                } else {
                    ToastUtils.showToast("上传失败");
                    return;
                }
                Glide.with(getActivity()).load(imageUrl).dontAnimate().into(titlePor);
                mySharedPreferences.edit().putString("avatar", Uri.fromFile(tempFile).toString()).commit();
                nameTitle.setVisibility(View.INVISIBLE);
                io.rong.imlib.model.UserInfo newUserInfo = new io.rong.imlib.model.UserInfo(yspUserInfo.getUuid(), yspUserInfo.getName(), Uri.parse(imageUrl));
                refreshUserInfo(newUserInfo);
                addImageToSDCard(tempFile, yspUserInfo.getUuid());
                //更新通信录中头像
                EventBus.getDefault().post(new UserAvatarChangedEvent(yspUserInfo.getUuid(), imageUrl));
                yspUserInfo.setAvatar(imageUrl);
                //更新本地头像url
                DatabaseUtil dataToastUtils = new DatabaseUtil();
                dataToastUtils.updateUserInfoById(mySharedPreferences.getString("uuid", ""), imageUrl);
                tempFile = null;
            } else {
                ToastUtils.showToast("上传失败");
            }
        }

        @Override
        public void onError(String errorMessage) {
            ToastUtils.showToast("上传失败");
        }

    }

    public void addImageToSDCard(File file, String str) {
        if (file != null && str != null) {
            CheckSdCard.getInstance().addBitmapToLocal(bitmap, str);
        }
    }


    /**
     * 添加了用户缓存更新方法(rongcloud)
     */
    private void refreshUserInfo(io.rong.imlib.model.UserInfo userInfo) {

        if (userInfo == null) {
            throw new IllegalArgumentException();
        }

        if (RongContext.getInstance() != null) {
            RongUserInfoManager.getInstance().setUserInfo(userInfo);
            RongContext.init(EnterApplication.getApp());
        }
        RongIM.getInstance().refreshUserInfoCache(userInfo);
        RongIM.getInstance().setCurrentUserInfo(userInfo);
        Log.e("arrive", "*********** here *************");
    }

    private void crop(Uri uri, boolean gallery) {
        flag = gallery;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDatection", true);
        String fileName = StringUtilSub.getPhotoFileName();
        tempShearFile = new File(imgCachePath, fileName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempShearFile));
        startActivityForResult(intent, PHOTO_REQUEST_CUT);

    }

    /**
     * 保存方法
     */
    public File saveBitmap(Bitmap bm) {
        File f = new File(Environment.getExternalStorageDirectory(),
                PHOTO_FILE_NAME);
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        PHOTO_FILE_NAME = StringUtilSub.getPhotoFileName();
        return f;
    }

    public interface AvatarUpdateInterface {
        void avatarUpdateEvent(String uuid, String uriStr);
    }
}
